package cn.itcast.controller;

import cn.itcast.domain.User;
import cn.itcast.exception.SysException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author Honglixi
 * @create 2021-03-20 21:36
 */
@Controller
@RequestMapping("/user")
public class UserController {
    /**
     * 返回String
     *
     * @param model
     * @return
     */
    @RequestMapping("/testString")
    public String testString(Model model) {
        System.out.println("tsetString方法执行了。。。");
        //模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("老八");
        user.setPassword("123");
        user.setAge(30);
        //model对象
        model.addAttribute("user", user);
        return "success";
    }

    /**
     * 返回void
     *
     * @param
     * @return
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("tsetVoid方法执行了。。。");
        //编写请求转发的程序
//        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        //重定向
//        response.sendRedirect(request.getContextPath()+"/index.jsp");
        //解决中文乱码
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //直接进行响应
        response.getWriter().println("Hello,老八");
        return;


    }

    /**
     * 返回ModelAndView
     *
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        ModelAndView mv = new ModelAndView();
        System.out.println("testModelAndView方法执行了。。。");
        //模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("哈拉少");
        user.setPassword("123321");
        user.setAge(30);

        //把user对象存储到mv对象中，也会把user对象存入到request对象
        mv.addObject("user", user);
        //跳转到哪个页面
        mv.setViewName("success");
        return mv;
    }

    /**
     * 关键字进行转发和重定向
     *
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect() {
        System.out.println("testForwardOrRedirect方法执行了。。。");

        //请求转发
//        return "forward:/WEB-INF/pages/success.jsp";
        //重定向
        return "redirect:index.jsp";
    }

    @RequestMapping("/testAjax")
    public @ResponseBody
    User testAjax(@RequestBody User user) {
        System.out.println("testAjax方法执行了。。。");
        //客户端发送ajax的请求，传的是json字符串，后端把json字符串封装到user对象中
        System.out.println(user);
        //做响应，模拟查询数据库
        user.setUsername("xixi");
        user.setAge(99);
        //
        return user;

    }

    @RequestMapping("/fileupload1")
    public String fileupload1(HttpServletRequest request) throws Exception {
        System.out.println("文件上传。。。");
        //使用fileupload组件完成文件上传
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            //创建该文件夹
            file.mkdirs();
        }
        //解析request对象，获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            //进行判断，当前item对象是否是上传文件项
            if (item.isFormField()) {
                //说明是普通表单项
            } else {
                //说明是上传文件项
                //获取上传文件的名称
                String filename = item.getName();
                //把文件的名称设置唯一值，uuid
                String uuid = UUID.randomUUID().toString().replace("-", " ");
                filename = uuid + "_" + filename;
                //完成文件的上传
                item.write(new File(path, filename));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }

    /**
     * SpringMVC方式文件上传
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload2")
    public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception {
        System.out.println("文件上传。。。");
        //使用fileupload组件完成文件上传
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            //创建该文件夹
            file.mkdirs();
        }
        String filename = upload.getOriginalFilename();
        //说明是上传文件项
        //获取上传文件的名称

        //把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", " ");
        filename = uuid + "_" + filename;
        //完成文件的上传
        upload.transferTo(new File(path,filename));
        return"success";
    }

    /**
     * 跨服务器文件上传
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload3")
    public String fileupload3( MultipartFile upload) throws Exception {
        System.out.println("跨服务器文件上传。。。");
        //定义上传文件服务器路径
        String path = "http://localhost:8088/uploads/";
        String filename = upload.getOriginalFilename();
        //说明是上传文件项
        //获取上传文件的名称

        //把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", " ");
        filename = uuid + "_" + filename;

        //创建客户端的对象
        Client client = Client.create();
        //和图片服务器进行连接
        WebResource webResource = client.resource(path + filename);
        //上传文件
        webResource.put(upload.getBytes());
        return"success";
    }
    @RequestMapping("/testException")
    public String testException( User user) throws SysException{
        System.out.println("testException方法执行了。。。");
        try {
            int a = 10/0;
        } catch (Exception e) {
            //打印异常信息
            e.printStackTrace();
            //抛出自定义异常信息
            throw new SysException("查询所有用户出现错误");
        }

        return "success";

    }
    @RequestMapping("/testInterceptor")
    public String testInterceptor(){
        System.out.println("testInterceptor执行了");
        return "success";
    }
}
